// pages/index/index.js
var wxCharts = require('../../utils/wxcharts.js');
var Api = require('../../utils/api.js');
var columnChart = null;
var targetData = [500, 20, 200, 50];
var currentData = [300, 10, 150, 30];

Page({
  data: {
    // 运动列表
    sports: ["静坐", "轻度运动", "中度运动", "重度运动", "高强度运动"],
    sportsVal: [1.2, 1.37, 1.55, 1.73, 1.9],
    sportIndex: 2,
    // 饮食类型
    tabs: ["早餐(0)", "午餐(0)", "晚餐(0)", "零食(0)"],
    // 食用列表
    eat: {
      date: "",
      uid: "",
      eat_score: 0,
      breakfast: [],
      lunch: [],
      dinner: [],
      snacks: [],
      score: {
        calorie_target: 2000,
        fat_target: 60,
        carbohydrate_target: 250,
        protein_target: 100,
        calorie_today: 0,
        fat_today: 0,
        carbohydrate_today: 0,
        protein_today: 0
      },
      exercise: 1.37
    },
    TabCur: 0,
    code: "",
    // 滑动删除相关（只保留需要在模板中使用的）
    modalName: null,
  },

  tabSelect(e) {
    this.setData({
      TabCur: e.currentTarget.dataset.id
    });
  },

  // 跳转到搜索页面
  goToSearch() {
    wx.navigateTo({
      url: '/pages/search/search'
    });
  },

  // 跳转到营养分析详情页面
  goToEatReport() {
    wx.navigateTo({
      url: '/pages/eat-report/eat-report'
    });
  },

  onShareAppMessage(o) {},

  onShow: function () {
    // 页面显示时，重置图表实例（从其他页面返回时 canvas 可能失效）
    columnChart = null;
    
    // 只在非首次加载时刷新数据
    if (this._isLoaded) {
      // 使用延迟确保页面已完全渲染
      setTimeout(() => {
        this.indexData();
      }, 100);
    }
  },

  onLoad: function (e) {
    this._isLoaded = true;
    this.indexData();
  },
  
  onHide: function () {
    // 页面隐藏时清理状态
    this._isLoading = false;
    this._touchDirection = null;
    this._touchStartX = 0;
  },
  
  onUnload: function () {
    // 页面卸载时清理图表实例
    columnChart = null;
  },

  indexData: function () {
    var that = this;
    
    // 防止重复请求
    if (this._isLoading) {
      console.log("正在加载中，跳过重复请求");
      return;
    }
    this._isLoading = true;
    
    // 从后端API获取饮食数据
    wx.request({
      url: Api.eat(),
      method: 'GET',
      timeout: 10000, // 10秒超时
      success: function(res) {
        console.log("获取饮食数据成功:", res.data);
        
        // 确保请求完成后重置加载标志
        that._isLoading = false;
        wx.stopPullDownRefresh();
        
        if (!res.data) {
          console.warn("返回数据为空");
          return;
        }
        
        const eatData = res.data;
        
        // 更新tabs标签显示数量
        const tabs = [
          `早餐(${eatData.breakfast ? eatData.breakfast.length : 0})`,
          `午餐(${eatData.lunch ? eatData.lunch.length : 0})`,
          `晚餐(${eatData.dinner ? eatData.dinner.length : 0})`,
          `零食(${eatData.snacks ? eatData.snacks.length : 0})`
        ];
        
        // 查找运动强度索引，如果找不到则使用默认值（中度运动，索引2）
        let sportIndex = that.data.sportsVal.indexOf(eatData.exercise);
        if (sportIndex === -1) {
          sportIndex = 2; // 默认选择"中度运动"
        }
        
        // 使用批量更新减少渲染次数
        that.setData({
          eat: eatData,
          tabs: tabs,
          sportIndex: sportIndex
        }, function() {
          console.log("页面数据更新完成");
        });
        
        // 设置图表数据
        targetData = [
          eatData.score.calorie_target || 2000,
          eatData.score.fat_target || 60,
          eatData.score.carbohydrate_target || 250,
          eatData.score.protein_target || 100
        ];
        currentData = [
          eatData.score.calorie_today || 0,
          eatData.score.fat_today || 0,
          eatData.score.carbohydrate_today || 0,
          eatData.score.protein_today || 0
        ];
        
        // 绘制图表
        that.canvas();
      },
      fail: function(err) {
        console.error("获取饮食数据失败:", err);
        
        // 确保请求失败后也重置加载标志
        that._isLoading = false;
        wx.stopPullDownRefresh();
        
        // 显示错误提示
        wx.showToast({
          title: '数据加载失败',
          icon: 'none',
          duration: 2000
        });
        
        // 使用当前数据绘制图表
        try {
          let sportIndex = that.data.sportsVal.indexOf(that.data.eat.exercise);
          if (sportIndex === -1) {
            sportIndex = 2; // 默认选择"中度运动"
          }
          
          if (that.data.sportIndex !== sportIndex) {
            that.setData({
              sportIndex: sportIndex
            });
          }
          
          targetData = [
            that.data.eat.score.calorie_target || 2000,
            that.data.eat.score.fat_target || 60,
            that.data.eat.score.carbohydrate_target || 250,
            that.data.eat.score.protein_target || 100
          ];
          currentData = [
            that.data.eat.score.calorie_today || 0,
            that.data.eat.score.fat_today || 0,
            that.data.eat.score.carbohydrate_today || 0,
            that.data.eat.score.protein_today || 0
          ];
          
          that.canvas();
        } catch (e) {
          console.error("使用默认数据渲染失败:", e);
        }
      }
    });
  },

  bindSportChange: function (e) {
    const that = this;
    const oldSportIndex = this.data.sportIndex; // 保存旧值，用于失败时恢复
    const newSportIndex = parseInt(e.detail.value); // 转换为数字类型
    const exercise = this.data.sportsVal[newSportIndex];
    
    console.log("选择运动强度 - 旧索引:", oldSportIndex, "新索引:", newSportIndex, "运动系数:", exercise);
    
    // 先立即更新界面显示
    this.setData({
      sportIndex: newSportIndex
    });
    
    // 更新后端的运动强度
    wx.request({
      url: Api.eat(),
      method: 'PUT',
      data: {
        exercise: exercise
      },
      success: function(res) {
        console.log("更新运动强度成功，返回数据:", res.data);
        console.log("返回的exercise值:", res.data ? res.data.exercise : 'undefined');
        console.log("返回的score:", res.data ? res.data.score : 'undefined');
        
        // 后端已经重新计算了营养目标，直接使用返回的数据
        if (res.data && res.data.score) {
          // 更新完整的饮食数据
          that.setData({
            eat: res.data
          }, () => {
            console.log("setData完成，当前sportIndex:", that.data.sportIndex);
            console.log("当前eat.exercise:", that.data.eat.exercise);
          });
          
          // 更新图表数据
          targetData = [
            res.data.score.calorie_target || 2000,
            res.data.score.fat_target || 60,
            res.data.score.carbohydrate_target || 250,
            res.data.score.protein_target || 100
          ];
          currentData = [
            res.data.score.calorie_today || 0,
            res.data.score.fat_today || 0,
            res.data.score.carbohydrate_today || 0,
            res.data.score.protein_today || 0
          ];
          
          console.log("更新后的目标数据:", targetData);
          console.log("更新后的当前数据:", currentData);
          
          // 重绘图表
          that.canvas();
          
          wx.showToast({
            title: '运动强度已更新',
            icon: 'success',
            duration: 1500
          });
        } else {
          console.error("返回数据格式错误:", res.data);
        }
      },
      fail: function(err) {
        console.error("更新运动强度失败:", err);
        // 失败时恢复到旧值
        that.setData({
          sportIndex: oldSportIndex
        });
        wx.showToast({
          title: '更新失败',
          icon: 'none'
        });
      }
    });
  },

  canvas: function () {
    var that = this;
    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }
    
    // 使用延迟渲染，确保 canvas 组件已经准备好
    setTimeout(function() {
      try {
        // 如果图表已存在且有效，尝试更新数据
        if (columnChart && columnChart.updateData && typeof columnChart.updateData === 'function') {
          try {
            columnChart.updateData({
              categories: ['总热量', '脂肪', '碳水物', '蛋白质'],
              series: [{
                name: '目标营养',
                data: targetData,
                format: function (val, name) {
                  return val;
                }
              }, {
                name: '今日营养',
                data: currentData,
                format: function (val, name) {
                  return val;
                }
              }]
            });
            console.log("图表数据更新成功");
            return;
          } catch (e) {
            console.log("更新图表数据失败，将重新创建图表", e);
            columnChart = null; // 清空失效的实例
          }
        }
        
        // 创建新图表实例
        columnChart = new wxCharts({
          canvasId: 'columnCanvas',
          type: 'column',
          animation: true,
          categories: ['总热量', '脂肪', '碳水物', '蛋白质'],
          series: [{
            name: '目标营养',
            data: targetData,
            format: function (val, name) {
              return val;
            }
          }, {
            name: '今日营养',
            data: currentData,
            format: function (val, name) {
              return val;
            }
          }],
          yAxis: {
            format: function (val) {
              return val;
            },
            title: '今日饮食数据',
            min: 0
          },
          xAxis: {
            disableGrid: true,
            type: 'calibration'
          },
          extra: {
            column: {
              width: 15
            }
          },
          width: windowWidth,
          height: 200,
        });
        console.log("图表创建成功");
      } catch (e) {
        console.error("图表渲染失败:", e);
      }
    }, 50); // 50ms 延迟，确保 DOM 已渲染
  },

  onPullDownRefresh: function () {
    console.log("Pull down to refresh data");
    this.indexData();
  },

  // 滑动删除 - 触摸开始
  ListTouchStart(e) {
    // 不使用 setData，直接保存到内存变量
    this._touchStartX = e.touches[0].pageX;
  },

  // 滑动删除 - 触摸移动
  ListTouchMove(e) {
    // 不使用 setData，只记录方向到内存变量，避免频繁渲染
    this._touchDirection = e.touches[0].pageX - this._touchStartX > -100 ? "right" : "left";
  },

  // 滑动删除 - 触摸结束
  ListTouchEnd(e) {
    // 只在触摸结束时更新一次状态
    if (this._touchDirection === "left") {
      this.setData({
        modalName: e.currentTarget.dataset.target,
      });
    } else {
      this.setData({
        modalName: null,
      });
    }
    // 清理内存变量
    this._touchDirection = null;
    this._touchStartX = 0;
  },

  // 图表触摸处理
  touchHandler(e) {
    console.log("图表触摸事件:", e);
    columnChart.touchHandler(e);
  },

  // 删除饮食记录
  eatDelete: function(e) {
    const that = this;
    const index = parseInt(e.currentTarget.dataset.index);
    const eatType = parseInt(e.currentTarget.dataset.eatType);
    
    console.log("删除饮食记录 - 索引:", index, "类型:", eatType);
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条饮食记录吗？',
      success: function(res) {
        if (res.confirm) {
          // 根据类型确定要操作的数组
          let arrayName = '';
          switch(eatType) {
            case 0:
              arrayName = 'breakfast';
              break;
            case 1:
              arrayName = 'lunch';
              break;
            case 2:
              arrayName = 'dinner';
              break;
            case 3:
              arrayName = 'snacks';
              break;
            default:
              console.error("未知的饮食类型:", eatType);
              return;
          }
          
          // 获取当前数组
          const currentArray = that.data.eat[arrayName];
          if (!currentArray || index >= currentArray.length) {
            console.error("索引越界或数组不存在");
            wx.showToast({
              title: '删除失败：数据异常',
              icon: 'none'
            });
            return;
          }
          
          // 创建新数组（删除指定项）
          const newArray = currentArray.filter((item, i) => i !== index);
          
          // 构建更新数据
          const updateData = {};
          updateData[arrayName] = newArray;
          
          // 更新到后端
          wx.request({
            url: Api.eat(),
            method: 'PUT',
            data: updateData,
            success: function(response) {
              console.log("删除饮食记录成功，返回数据:", response.data);
              
              // 直接使用后端返回的最新数据更新界面（包括重新计算的营养数据）
              if (response.data && response.data.score) {
                // 更新tabs标签显示数量
                const tabs = [
                  `早餐(${response.data.breakfast ? response.data.breakfast.length : 0})`,
                  `午餐(${response.data.lunch ? response.data.lunch.length : 0})`,
                  `晚餐(${response.data.dinner ? response.data.dinner.length : 0})`,
                  `零食(${response.data.snacks ? response.data.snacks.length : 0})`
                ];
                
                that.setData({
                  eat: response.data,
                  tabs: tabs,
                  modalName: null
                });
                
                // 更新图表
                targetData = [
                  response.data.score.calorie_target || 2000,
                  response.data.score.fat_target || 60,
                  response.data.score.carbohydrate_target || 250,
                  response.data.score.protein_target || 100
                ];
                currentData = [
                  response.data.score.calorie_today || 0,
                  response.data.score.fat_today || 0,
                  response.data.score.carbohydrate_today || 0,
                  response.data.score.protein_today || 0
                ];
                that.canvas();
                
                wx.showToast({
                  title: '删除成功',
                  icon: 'success',
                  duration: 1500
                });
              } else {
                // 如果后端没有返回完整数据，则重新加载
                that.indexData();
                that.setData({
                  modalName: null
                });
              }
            },
            fail: function(err) {
              console.error("删除饮食记录失败:", err);
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  }
});
